<?php

namespace addons\shopro\controller\v1\goods;

use addons\shopro\controller\Base;
use addons\shopro\model\Config;
use app\admin\model\shopro\order\Order;
use app\admin\model\shopro\order\OrderExpress;
use think\Db;
/**
 * 商品修改申请
 */
class Xg extends Base
{
    protected $noNeedLogin = ['get','select','fahuo'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

    }
    public function set(){
        $userid = $this->auth->id;
        $good_id =  $this->request->get('good_id');
        $content =  $this->request->get('content');
        if (empty($content)){$this->error('修改内容不存在');}
        $good_info = Db::name('shopro_goods')->where('id',$good_id)->find();
        if (empty($good_info)){$this->error('商品不存在');}
        $info = Db::name('shopro_user_store')->where('user_id',$userid)->where('store_id',$good_info['shopro_store_id'])->find();
        if (empty($info)){$this->error('对应商家无权限');}
        $data = array(
            'goods_id'=>$good_id,
            'store_id'=>$good_info['shopro_store_id'],
            'user_id'=>$userid,
            'content'=>$content,
            'status'=>0,
            'createtime'=>time(),
        );

        Db::name('shopro_goods_xg')->insert($data);

        $this->success('提交申请成功',[]);
    }

    public function select()
    {
        $page = $this->request->get('page');
        $limit = $this->request->get('limit');
        $name = $this->request->get('name');
        $total = Db::name('shopro_express')
            ->whereOr('name', 'like', "%$name%")
            ->whereOr('code', 'like', "%$name%")
            ->order('weigh desc')
            ->page($page)
            ->limit($limit)
            ->count();

        $list = Db::name('shopro_express')
            ->field('name, code')
            ->whereOr('name', 'like', "%$name%")
            ->whereOr('code', 'like', "%$name%")
            ->order('weigh desc')
            ->page($page)
            ->limit($limit)
            ->select();

        $list = collection($list)->toArray();

        $this->success('快递公司', $list);
    }
    /**
     * 手动发货
     *
     * @param int $id     订单ID
     * @param string  $item_ids 订单中需发货的商品
     * @param int $express_id  发货包裹ID
     * @param string $express_name  快递公司名称
     * @param string $express_code  物流公司编号
     * @param string $express_no    运单号
     */
    public function fahuo(){

        $express_name = $this->request->post('express_name', '');
        $express_code = $this->request->post('express_code', '');
        $express_no = $this->request->post('express_no', '');
        $order_id = $this->request->post('order_id', '');

        if (empty($express_name) || empty($express_code) ||empty($express_no) ||empty($order_id)){$this->error('参数缺失');}


        $order_info =  Db::name('shopro_order')->where('id',$order_id)->find();
        if (empty($order_info)){$this->error('订单不存在');}
        $order_item_info =  Db::name('shopro_order_item')->where('order_id',$order_id)->where('dispatch_status',1)->find();
        if (!empty($order_item_info)){$this->error('当前订单已发货');}
        //处理自动发货

        $send_time = time();
        //更新订单商品
        Db::name('shopro_order_item')->where(['order_id'=>$order_id])->update([
            'express_name' => $express_name,
            'express_code' => $express_code,
            'express_no' => $express_no,
            'ext' => json_encode(['send_time'=>$send_time]),
            'dispatch_status' => 1,
        ]);

        //添加快递包裹
        Db::name('shopro_order_express')->insert([
            'user_id' => $order_info['user_id'],
            'order_id' => $order_info['id'],
            'express_name' => $express_name,
            'express_code' => $express_code,
            'express_no' => $express_no,
            'createtime' => time(),
            'updatetime' => time(),
        ]);
        
        $express_id = Db::name('shopro_order_express')->getLastInsID();







        // 添加自动确认收货队列
        $config = Db::name('shopro_config')->where('name', 'order')->find();
        $config = isset($config['value']) ? json_decode($config['value'], true) : [];
        $close_days = (isset($config['order_auto_confirm']) && $config['order_auto_confirm'] > 0)
            ? $config['order_auto_confirm'] : 10;       // 单位天

        //获取订单
        $order_model = new Order();
        $order = $order_model->where('id', $order_id)->find();
        //循环处理
        $item_lists = \app\admin\model\shopro\order\OrderItem::where(['order_id'=>$order_id])->select();
        foreach ($item_lists as $key => $item) {
            //file_put_contents("fahuo.json",json_encode(['order'=>$order,'order_item'=>$item]).PHP_EOL, FILE_APPEND|LOCK_EX);
            // 除了自提/到店（核销码自动收货，核销码有过期时间），之外，设置确认收货队列
            if ($item['dispatch_type'] != 'selfetch') {
                $params = ['order' => $order, 'item' => $item];
                \think\Queue::later(($close_days * 86400), '\addons\shopro\job\OrderAutoOper@autoConfirm', $params, 'shopro');

                //file_put_contents("fahuo.json",json_encode(['close_days' => $close_days * 86400]).PHP_EOL, FILE_APPEND|LOCK_EX);
            }
        }




        // 获取包裹
        $orderExpress = OrderExpress::with('order')->where('id', $express_id)->find();
        $expressLib = new \addons\shopro\library\Express();
        // 重新订阅
        $expressLib->subscribe([
            'express_code' => $orderExpress['express_code'],
            'express_no' => $orderExpress['express_no']
        ], $orderExpress, $orderExpress->order);





        

        $this->success('发货成功');
    }
    /**
     * 处理发货前置检查流程
     *
     * @param int $id     订单ID
     * @param string  $item_ids 订单中需发货的商品
     * @param int $express_id  发货包裹ID
     * @param string $express_name  快递公司名称
     * @param string $express_code  物流公司编号
     * @param string $express_no    运单号
     */
    private function handleDeliveryBefore($id, $item_ids, $express_id)
    {
        $this->dd = new \app\admin\model\shopro\order\Order;
        $order = $this->dd->payed()->where('id', $id)->find();

        if (!$order) {
            $this->error('订单不存在或未支付');
        }
        if ($item_ids == '') {
            $this->error('请选择待发货的商品');
        }
        //拼团中商品可以发货
//        if ($order->status_code === 'groupon_ing') {
//            $this->error('该商品还未拼团成功,暂不能发货');
//        }
        // 查询要发货的商品
        if ($item_ids == 'all') {   // 选中所有商品
            $where = [
                'order_id' => $id,
                'dispatch_type' => 'express'        // 必须是物流快递的商品
            ];
        } else {
            $where = [            // 选中分包裹商品
                'order_id' => $id,
                'id' => ['in', $item_ids],
                'dispatch_type' => 'express'
            ];
        }

        // 订单包裹
        $orderExpress = null;
        if ($express_id) {
            // 修改包裹
            $orderExpress = OrderExpress::where('id', $express_id)->find();
            if (!$orderExpress) {
                $this->error('包裹不存在');
            }
        }

        $dispatchWhere[] =  \app\admin\model\shopro\order\OrderItem::DISPATCH_STATUS_NOSEND;

        if ($express_id) {
            // 可以修改已发货的商品
            $dispatchWhere[] = \app\admin\model\shopro\order\OrderItem::DISPATCH_STATUS_SENDED;
        }
        $where['dispatch_status'] = ['in', $dispatchWhere];

        $item_lists = \app\admin\model\shopro\order\OrderItem::where($where)->select();

        if (!$item_lists) {
            $this->error('没有物流发货的商品');
        }
        return [$order, $orderExpress, $item_lists];
    }

    /**
     * 处理发货后置流程
     *
     * @param object $order     订单
     * @param array  $item_lists 订单中待发货的商品
     * @param object $orderExpress  发货包裹
     * @param string $express_name  快递公司名称
     * @param string $express_code  物流公司编号
     * @param string $express_no    运单号
     */
    private function handleDeliveryAfter($order, $item_lists, $orderExpress, $express_name, $express_code, $express_no)
    {
        $this->dd = new \app\admin\model\shopro\order\Order;
        if (!$express_name || !$express_code || !$express_no) {
            $this->error('请填写完整发货信息');
        }
        $needSubscribe = true;
        if ($orderExpress && $orderExpress->express_no == $express_no && $orderExpress->express_code == $express_code) {
            // 没有编辑快递信息，不需要重新订阅快递
            $needSubscribe = false;
        }
        $orderExpress =  Db::transaction(function () use ($order, $item_lists, $orderExpress, $express_name, $express_code, $express_no) {
            foreach ($item_lists as $key => $item) {
                $order->sendItem($order, $item, [
                    "express_name" => $express_name,
                    "express_code" => $express_code,
                    "express_no" => $express_no,
                    "oper" => $this->auth->getUserInfo(),
                    "oper_type" => 'admin',
                ]);
            }

            if (!$orderExpress) {
                // 添加包裹
                $orderExpress = new OrderExpress();
                $orderExpress->user_id = $order->user_id;
                $orderExpress->order_id = $order->id;
            } else {
                // 查询选择的包裹中未被选中的商品，改为未发货
                \app\admin\model\shopro\order\OrderItem::where('order_id', $order['id'])
                    ->where('id', 'not in', array_column($item_lists, 'id'))
                    ->where('express_no', $orderExpress->express_no)
                    ->where('express_code', $orderExpress->express_code)->update([
                        'express_name' => null,
                        'express_code' => null,
                        'express_no' => null,
                        'dispatch_status' => \app\admin\model\shopro\order\OrderItem::DISPATCH_STATUS_NOSEND
                    ]);
            }

            $orderExpress->express_name = $express_name;
            $orderExpress->express_code = $express_code;
            $orderExpress->express_no = $express_no;
            $orderExpress->save();

            // 查询已经没有商品的包裹，并且删除
            OrderExpress::whereNotExists(function ($query) use ($order) {
                $order_table_name = (new OrderExpress())->getQuery()->getTable();
                $table_name = (new \app\admin\model\shopro\order\OrderItem())->getQuery()->getTable();
                $query->table($table_name)->where($table_name . '.express_no=' . $order_table_name . '.express_no')
                    ->where($table_name . '.express_code=' . $order_table_name . '.express_code')
                    ->where('order_id', $order['id']);
            })->where('order_id', $order['id'])->delete();

            return $orderExpress;
        });
        return [$orderExpress, $needSubscribe];
    }






}
